package com.example.onlinefood.service;

import com.example.onlinefood.domain.Order;
import com.example.onlinefood.domain.OrderEvaluation;
import com.example.onlinefood.domain.OrderItem;
import com.example.onlinefood.mapper.OrderEvaluationMapper;
import com.example.onlinefood.mapper.OrderItemMapper;
import com.example.onlinefood.mapper.OrderMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.List;

@Service
public class OrderService {
    @Resource
    private OrderMapper orderMapper;
    @Resource
    private OrderItemMapper orderItemMapper;
    
    @Resource
    private OrderEvaluationMapper orderEvaluationMapper;

    @Transactional
    public Integer createOrder(Order order, List<OrderItem> items) {
        orderMapper.insert(order);
        for (OrderItem it : items) {
            it.setOrderId(order.getId());
        }
        if (items != null && !items.isEmpty()) {
            orderItemMapper.insertBatch(items);
        }
        return order.getId();
    }

    public Order getById(Integer id) { return orderMapper.findById(id); }
    public List<Order> listByUser(Integer userId) { return orderMapper.findByUserId(userId); }
    public List<OrderItem> listItems(Integer orderId) { return orderItemMapper.findByOrderId(orderId); }
    
    @Transactional
    public boolean cancelOrder(Integer orderId, Integer userId) {
        Order order = orderMapper.findById(orderId);
        if (order == null || !order.getUserId().equals(userId)) {
            return false;
        }
        
        // 检查订单状态是否为pending
        if (!"pending".equals(order.getStatus())) {
            return false;
        }
        
        // 检查订单是否在一分钟内创建
        LocalDateTime now = LocalDateTime.now();
        long minutes = ChronoUnit.MINUTES.between(order.getOrderDate(), now);
        if (minutes >= 1) {
            return false;
        }
        
        // 更新订单状态为canceled
        return orderMapper.updateStatus(orderId, "canceled") > 0;
    }
    
    @Transactional
    public boolean deleteOrder(Integer orderId, Integer userId) {
        Order order = orderMapper.findById(orderId);
        if (order == null || !order.getUserId().equals(userId)) {
            return false;
        }
        
        // 只允许删除已取消或已完成的订单
        if (!"canceled".equals(order.getStatus()) && !"completed".equals(order.getStatus()) && !"COMPLETED".equals(order.getStatus())) {
            return false;
        }
        
        // 先删除订单关联的订单项
        orderItemMapper.deleteByOrderId(orderId);
        
        // 如果订单已评价，还需要删除评价
        OrderEvaluation evaluation = orderEvaluationMapper.findByOrderId(orderId);
        if (evaluation != null) {
            orderEvaluationMapper.deleteByOrderId(orderId);
        }
        
        // 再删除订单
        return orderMapper.deleteById(orderId) > 0;
    }
    
    @Transactional
    public boolean updateOrderStatus(Integer orderId, Integer userId, String newStatus) {
        Order order = orderMapper.findById(orderId);
        if (order == null || !order.getUserId().equals(userId)) {
            return false;
        }
        
        // 只允许将pending状态的订单更新为completed状态
        if (!"pending".equals(order.getStatus()) || !"completed".equals(newStatus)) {
            return false;
        }
        
        // 更新订单状态
        return orderMapper.updateStatus(orderId, newStatus) > 0;
    }
    
    public void completeOrder(Integer orderId) {
        Order order = orderMapper.findById(orderId);
        if (order != null) {
            orderMapper.updateStatus(orderId, "COMPLETED");
        }
    }
    
    // 添加订单评价
    @Transactional
    public void addOrderEvaluation(Integer orderId, Integer userId, Integer score, String content) {
        // 检查订单是否存在并且已完成
        Order order = orderMapper.findById(orderId);
        if (order == null || !"COMPLETED".equalsIgnoreCase(order.getStatus())) {
            throw new RuntimeException("订单不存在或未完成，无法评价");
        }
        
        // 检查是否已经评价过
        OrderEvaluation existingEvaluation = orderEvaluationMapper.findByOrderId(orderId);
        if (existingEvaluation != null) {
            throw new RuntimeException("该订单已经评价过");
        }
        
        // 创建新评价
        OrderEvaluation evaluation = new OrderEvaluation();
        evaluation.setOrderId(orderId);
        evaluation.setUserId(userId);
        evaluation.setScore(score);
        evaluation.setContent(content);
        
        // 保存评价
        orderEvaluationMapper.insert(evaluation);
    }
    
    // 查询订单评价
    public OrderEvaluation getOrderEvaluation(Integer orderId) {
        return orderEvaluationMapper.findByOrderId(orderId);
    }
}


